#include <iostream>
#include <time.h>
#include <thread>
#include <chrono>
#include <signal.h>
#include "event.h"

static struct timeval tv1 = { 1, 0 };
static struct timeval tv2 = { 1, 500000 };

// 定时器回调函数
void timer1_cb(evutil_socket_t fd, short what, void *arg) {
    std::cout << "[timer1_cb] time: " << time(NULL) << std::endl;

    // 重新添加到libevent中，类似于持久化
    event *ev = (event*)arg;
    if (!evtimer_pending(ev, &tv1)) {
        evtimer_del(ev);
        evtimer_add(ev, &tv1);
    }
}

// 定时器回调函数
void timer2_cb(evutil_socket_t fd, short what, void *arg) {
    std::cout << "[timer2_cb] time: " << time(NULL) << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(3));
}

// 定时器回调函数
void timer3_cb(evutil_socket_t fd, short what, void *arg) {
    std::cout << "[timer3_cb] time: " << time(NULL) << std::endl;
}

int main(int argc, char* argv[])
{
#ifdef _WIN32
    // 初始化socket库
    WSADATA wsa;
    WSAStartup(MAKEWORD(2, 2), &wsa);
#else
    // 忽略管道信号，因为发送数据给已关闭的socket会生成SIGPIPE信号，导致进程退出
    if (signal(SIGPIPE, SIG_IGN) == SIG_ERR)
        return -1;
#endif

    std::cout << "libevent timer test" << std::endl;
    // 创建libevent上下文
    event_base *base = event_base_new();
    if (!base) {
        std::cout << "event_base_new failed" << std::endl;
        return -1;
    }
    std::cout << "event_base_new success" << std::endl;

    /**
     * #define evtimer_new(b, cb, arg)	event_new((b), -1, 0, (cb), (arg))
     * #define evtimer_add(ev, tv)		event_add((ev), (tv))
     * #define evtimer_del(ev)			event_del(ev)
     */
    // 创建定时器事件
    event *ev1 = evtimer_new(base, timer1_cb, event_self_cbarg());
    if (!ev1) {
        std::cout << "evtimer_new ev1 failed" << std::endl;
        return -1;
    }
    evtimer_add(ev1, &tv1);

    // 持久化事件
    event *ev2 = event_new(base, -1, EV_PERSIST, timer2_cb, NULL);
    if (!ev2) {
        std::cout << "event_new ev2 failed" << std::endl;
        return -1;
    }
    evtimer_add(ev2, &tv2);

    // 超时优化，默认event用二叉堆（完全二叉树）存储，插入删除复杂度 O(logn)
    // 优化到双向队列，插入删除复杂度 O(1)
    struct timeval tv_in = { 3, 0 };
    const timeval *tv3 = event_base_init_common_timeout(base, &tv_in);
    event *ev3 = event_new(base, -1, EV_PERSIST, timer3_cb, NULL);
    evtimer_add(ev3, tv3);      // 插入性能 O(1)

    // 事件分发处理
    event_base_dispatch(base);

    // 释放资源
    event_free(ev1);
    event_free(ev2);
    event_free(ev3);
    event_base_free(base);

#ifdef _WIN32
    WSACleanup();
#endif

    return 0;
}
